#!/usr/bin/python


__author__='yingnn'

'split bed file to n parts'

import sys

# if sys.argv[1] == None: # IndexError: list index out of range
	# print sys.argv[0], 'in.bed num' 
	# exit()
	


fname=sys.argv[1]
n=int(sys.argv[2])

data=list()
f=open(fname)
for row in f:
	data.append(row.strip().split('\t')[:3]) # use append, not data[i] # note X Y not int
f.close()

leng=0

for i in range(len(data)):
	# print i, data[i]
	data[i][1:3]=map(int, data[i][1:3])
	leng+=data[i][2]-data[i][1]
# for chr, start, end in data:
	# leng+=end-start

len_small=int(leng/n)
print leng, len_small


i=0
len_tmp=0

f=open(str(i), 'w')

for chr,start,end in data:

	len_tmp+=end-start
	while True:
		if len_tmp > len_small:
			end0=end+len_small-len_tmp
			interval='\t'.join(map(str, [chr, start, end0]))+'\n'
			f.write(interval)
			f.close()
			start=end0
			len_tmp-=len_small
			i+=1
			f=open(str(i), 'w')
		else:
			interval='\t'.join(map(str, [chr, start, end]))+'\n'
			f.write(interval)
			break
		
f.close()
